package com.hxs.hxsserver.common;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Andi
 */
public class EnumHandler<E extends Enum<E> & Option> extends BaseTypeHandler<E> {
    private Class<E> clazz;

    public EnumHandler(Class<E> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setInt(i, parameter.origin());
        }
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String column) throws SQLException {
        int value = resultSet.getInt(column);
        return getEnum(value);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int index) throws SQLException {
        int value = resultSet.getInt(index);
        return getEnum(value);
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int index) throws SQLException {
        int value = callableStatement.getInt(index);
        return getEnum(value);
    }

    private E getEnum(int value) {
        E[] enums = clazz.getEnumConstants();
        for (E item : enums) {
            if (item.origin() == value) {
                return item;
            }
        }
        return null;
    }
}
